package breeze.update.album;
 
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.content.IntentSender;
import android.Manifest;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class MainActivity extends Activity {
	
	private TextView textView;
	
	private FileUtils utils;
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		if(Build.VERSION.SDK_INT>=23){
			if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
				requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
			}
		}
        init();
    }

	private void init() {
		utils = new FileUtils(this);
		textView = findViewById(R.id.activitymainTextView1);
		textView.setText(getString(R.string.introduce));
	}
	
	public void update(View view){
		update();
	}
	
	public void hide(View view){
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");
		startActivityForResult(intent.createChooser(intent,"Select Photo"),100);
	}
	
	private void update(){
		MediaScannerConnection.scanFile(this,new String[]{Environment.getExternalStorageDirectory().getAbsolutePath()},null,null);
		Toast.makeText(this,"刷新成功",Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflate = new MenuInflater(this);
		inflate.inflate(R.menu.main_menu,menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if(id == R.id.join_qq){
			if(!joinQQGroup()){
				Toast.makeText(MainActivity.this,"未安装手Q或安装的版本不支持",Toast.LENGTH_SHORT).show();
			}
		}else if(id == R.id.open_code){
			Intent intent = new Intent();
			intent.setData(Uri.parse("https://gitee.com/jasontom/refresh-the-album"));
			startActivity(intent);
		}else if(id == R.id.hidden){
			startActivity(new Intent(MainActivity.this,HiddenAlbumActivity.class));
		}
		return super.onOptionsItemSelected(item);
	}
	
	public boolean joinQQGroup() {
		Intent intent = new Intent();
		intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D" + "tKOeq1pdzPZHUCSdferPLqXcfzu-RvN5"));
		// 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
		try {
			startActivity(intent);
			return true;
		} catch (Exception e) {
			// 未安装手Q或安装的版本不支持
			return false;
		}
	}
	
	private void toast(String str){
		Toast.makeText(this,str,Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 100 && resultCode == Activity.RESULT_OK){
			File file = new File(getFile(data.getData()));
			String file_nomedia = file.getParent()+"/.nomedia";
			showIsHideAlbum(file.getParentFile(),file_nomedia);
		}else if(requestCode == 100 && resultCode == Activity.RESULT_CANCELED){
			
		}else if(requestCode == 100){
			toast("获取图片失败!");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void showIsHideAlbum(File parent,String filepath){
		final File file = new File(filepath);
		new AlertDialog.Builder(this)
		.setTitle("提示")
		.setMessage("确定要隐藏 "+parent.getName()+"相册 吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface p1, int p2) {
					try {
						file.createNewFile();
						toast("隐藏成功");
						utils.addData(file.getAbsolutePath());
						update();
					} catch (IOException e) {
						toast("隐藏失败："+e.toString());
					}
				}
			})
		.setNegativeButton("取消",null)
		.show();
	}
	
	private String getFile(Uri uri){
		String filepath;
		String[] h_file = new String[]{MediaStore.MediaColumns.DATA,MediaStore.MediaColumns.DISPLAY_NAME};
		String[] l_file = new String[]{MediaStore.MediaColumns.DATA};
		ContentResolver cr = getContentResolver();
		Cursor cursor = null;
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
			cursor = cr.query(uri,h_file,null,null);
		}else{
			cursor = cr.query(uri,l_file,null,null);
		}
		if(cursor!=null){
			cursor.moveToFirst();
			filepath = cursor.getString(cursor.getColumnIndex(l_file[0]));
			return filepath;
		}
		return null;
	}
	
} 
